// 定义事件总线类
export class EventBus {
  private static instance: EventBus
  // 用于存储事件处理函数的映射
  private events: Record<string, ((...args: any[]) => void)[]> = {}

  // 获取单例实例
  public static getInstance(): EventBus {
    if (!EventBus.instance) {
      EventBus.instance = new EventBus()
    }
    return EventBus.instance
  }

  // 订阅事件
  on(eventName: string, callback: (...args: any[]) => void): void {
    if (!this.events[eventName]) {
      this.events[eventName] = []
    }
    this.events[eventName].push(callback)
  }

  // 取消订阅事件
  off(eventName: string, callback?: (...args: any[]) => void): void {
    if (this.events[eventName]) {
      if (callback) {
        this.events[eventName] = this.events[eventName].filter(
          (cb) => cb !== callback,
        )
      } else {
        delete this.events[eventName]
      }
    }
  }

  // 触发事件
  emit(eventName: string, ...args: any[]): void {
    const callbacks = this.events[eventName]
    if (callbacks) {
      callbacks.forEach((callback) => callback(...args))
    }
  }
}

// 初始化并导出事件总线实例
export const eventBus = EventBus.getInstance()
